package com.yunzhou.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map.Entry;

public class HttpRequest {
	private Log log = new LogFactory().getLog("custom_huangwm");
	public  JSONObject CallApiPost(String url,String params){
		String responseText = "";
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		CloseableHttpResponse httpResponse = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-Type","application/json-patch+json");
			BasicHttpEntity requestBody = new BasicHttpEntity();
			requestBody.setContent(new ByteArrayInputStream(params.getBytes("UTF-8")));
			requestBody.setContentLength(params.getBytes("UTF-8").length);
			httpPost.setEntity(requestBody);
			
			httpResponse = httpClient.execute(httpPost);
			HttpEntity entity = httpResponse.getEntity();
			InputStream out = entity.getContent();
			
//			byte[] buff = new byte[2048];
//	        int size = 0;
//	        while((size = out.read(buff))!=-1){
//	        	responseText += new String(buff,"UTF-8").trim();
//	        };
//	        log.info("InputStream responseText");
			
            if (entity != null) {
            	responseText = EntityUtils.toString(entity, "UTF-8");
            }
			
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
			//httpclient.getConnectionManager().shutdown();
			if (httpResponse != null) {
               try {
            	   httpResponse.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (httpClient != null) {
               try {
                   httpClient.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
		}
		return  JSONObject.parseObject(responseText);
	}
	
	public String postData(String url, JSONObject param) {
		log.info("=============postData start================");
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            
            for (Entry<String,Object> entry : param.entrySet()) {
            	log.info(entry.getKey()+">>>"+entry.getValue());
                builder.addParameter(entry.getKey(), JSONObject.toJSONString(entry.getValue()));
            }

            HttpPost post = new HttpPost(builder.build());

            response = httpClient.execute(post);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = entityToString(entity);
            }
            
        } catch (URISyntaxException e) {
            e.printStackTrace();
            log.info("URISyntaxException>>"+e.getMessage());
        } catch (ClientProtocolException e) {
        	log.info("ClientProtocolException>>"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("IOException>>"+e.getMessage());
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        log.info("=============postData end================");
        return result;
    }
	
	public String getData(String url, JSONObject param) {
		log.info("=============getData start================");
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);

            for (Entry<String,Object> entry : param.entrySet()) {
            	log.info(entry.getKey()+">>>"+entry.getValue());
                builder.addParameter(entry.getKey(), JSONObject.toJSONString(entry.getValue()));
            }

            HttpGet post = new HttpGet(builder.build());

            response = httpClient.execute(post);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = entityToString(entity);
            }
            return result;
        }  catch (URISyntaxException e) {
            e.printStackTrace();
            log.info("URISyntaxException>>"+e.getMessage());
        } catch (ClientProtocolException e) {
        	log.info("ClientProtocolException>>"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("IOException>>"+e.getMessage());
        }  finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("=============getData end================");
        return null;
    }
	
    private String entityToString(HttpEntity entity) throws IOException {
        String result = null;
        if (entity != null) {
            long lenth = entity.getContentLength();
            if (lenth != -1 && lenth < 2048) {
                result = EntityUtils.toString(entity, "UTF-8");
            } else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while ((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }
    
    public String getCurrentTime() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":"
                + (timestamp.toString()).substring(17, 19);
        return currenttime;
    }

    public String getCurrentDate() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-"
                + (timestamp.toString()).substring(8, 10);
        return currentdate;
    }

    /**
       * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS
     * @return		当前日期时间
     */
    public String getCurDateTime() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        return (timestamp.toString()).substring(0, 19);
    }

    /**
     * 获取时间戳   格式如：19990101235959
     * @return
     */
    public String getTimestamp(){
        return getCurDateTime().replace("-", "").replace(":", "").replace(" ", "");
    }

    public int getIntValue(String v, int def) {
        try {
            return Integer.parseInt(v);
        } catch (Exception ex) {
            return def;
        }
    }
}
